// pages/enterInfo/enterInfo.js
var app = getApp();
var model = require('../../utils/model/model.js');   
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    userInfo: '',
    modelData: {
      showModal: false,
      signle: true,
      signleBtnTxt: "确定",
      content: '',
    },
    formlist: [
      { label: '个人资料', type: 'label' },
      { isrequire: true, label: '姓名', key: 'name', valueType: 'text', tips: '请填写', type: 'input' },
      { isrequire: true, label: '性别', key: 'sex', valueType: 'text', tips: '请选择',  type: 'select', data: ['男', '女'] },
      { isrequire: true, label: '籍贯', key: 'homeplace', valueType: 'text', tips: '请选择', type: 'select', mode: 'region' },
      
      { isrequire: true, label: '身份证号', key: 'cardId', maxlength: 18, valueType: 'text', tips: '请填写', type: 'input', reg:'^[1-9]\\d{5}((1[89]|20)\\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}([\\dx]|[\\dX])$' },
      { isrequire: true, label: '出生年月', key: 'birthday', valueType: 'text', tips: '请选择', type: 'select', mode: 'date' },
      { isrequire: true, label: '居住地址', key: 'address', valueType: 'text', tips: '请选择', type: 'select', mode: 'region' },
      { isrequire: true, label: '街道', key: 'street', valueType: 'text', tips: '请填写', type: 'input' },
      // { isrequire: true, label: '详细地址', key: 'name', valueType: 'text', tips: '请选择', type: 'input' },
      // { isrequire: true, label: '手机号', key: 'phone', maxlength: 11,  valueType: 'text', tips: '请填写', type: 'input', reg: "^1[34578][0-9]{9}$" },
      
      { isrequire: true, label: '行业', key: 'type', valueType: 'text', tips: '请选择', type: 'select', rangeKey:'name', data: []},
      { label: '其他信息', type: 'label' },
      { isrequire: false, label: '工作单位', key: 'companyName', valueType: 'text', tips: '请填写', type: 'input' },
      { isrequire: false, label: '工作地址', key: 'workingAddress', valueType: 'text', tips: '请填写', type: 'input' },
      { isrequire: false, label: '职位', key: 'job', valueType: 'text', tips: '请填写', type: 'input' },
      { isrequire: false, label: '经营范围', key: 'businessScope', valueType: 'text', tips: '请填写', type: 'input' },
      { isrequire: false, label: '兴趣', key: 'hobby', valueType: 'text', tips: '请选择', type: 'input', url: '/pages/hobby/hobby'},
      { isrequire: false, label: '车辆详情', key: 'carDetail', valueType: 'text', tips: '请选择', type: 'input', url: '/pages/carInfo/carInfo' },
      { isrequire: false, label: '教育经历', key: 'educationExp', valueType: 'text', tips: '请选择', type: 'input', url: "/pages/educationExp/educationExp" },
      { label: '更多信息', type: 'label' }
    ],
    formData:{
      id: '',
      name:'',
      sex:'',
      imgUrl:'',
      homeplace:'',
      street:'',
      cardId:'',
      birthday:'',
      address:['江苏省','连云港市','连云区'],
      job:'',
      businessScope:'',
      companyName:'',
      type:'',
      // phone:'',
      carDetail:'',
      educationExp:'',
      workingAddress:'',
      hobby:'',
      highSchoolName: "",
      highSchoolStart: '',
      highSchoolEnd: '',
      universityName: '',
      universityStart: '',
      universityEnd: '',
      graduateStudentName: '',
      graduateStudentStart: '',
      graduateStudentEnd: '',
      topSchoolName: '',
      topSchoolStart: '',
      topSchoolEnd: '',
      brandCar: "",
      plateNumber: '',
      carColor: '',
      seat: '',
      // receiptCode: '',
      anyMore:'',
      brandCarName:''
    },
    showData:{type:''},
    keys: '',
    inputShow: false,
    key: 'name', 
    valueType: 'text',
    currentInput: {},
    active: '',
    canSubmit:false,
    isHome:false,
    error: 1
  },
  bindPickerChange: function (e) {
    var item = e.currentTarget.dataset.item;
    if (item.data){
      if(item.rangeKey){
        this.data.formData[item.key] = item.data[e.detail.value].id;
        this.data.showData[item.key] = item.data[e.detail.value][item.rangeKey]
      }else{
        this.data.formData[item.key] = item.data[e.detail.value]
      }
    }else{
      this.data.formData[item.key] = e.detail.value
    }
    
    this.setData({
      formData: this.data.formData,
      showData: this.data.showData
    })
    this.changeValue();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.isHome){
      this.setData({
        isHome:true
      })
    }
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        userInfo: JSON.parse(wx.getStorageSync('userInfo'))
      })
    }
    this.data.formData.id = this.data.userInfo.id;
    model.init.apply(this, ['modelData']);
    if(options.flag!=undefined){
      var that = this;
      wx.getStorage({
        key: 'personalInfo',
        success: function (res) {
          that.setData({
            formData: res.data
          })
          that.changeValue();
          that.checkEducation();
          that.getAllType();
          wx.removeStorage({
            key: 'personalInfo'
          })
        }
      })
    }else{
      for (var j in this.data.userInfo) {
        console.log(this.data.userInfo)
        if (this.data.userInfo[j]){
          if (this.data.formData[j]!=undefined){
            this.data.formData[j] = this.data.userInfo[j];
          }
        }
      }
      this.setData({
        formData: this.data.formData
      })
      this.changeValue();
      this.checkEducation();
      this.getAllType();
      this.getIs();
    }
    
  },
  getIs: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'menu/index',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            error: res.data.error
          })
        }
      }
    })
  },
  getAllType: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyIndustryResource/all',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          var flag=true;
          if (that.data.formData.type){
            res.data.data.forEach(function(ele,index){
              if (ele.id == that.data.formData.type){
                that.setData({
                  'showData.type': ele.name,
                  'formlist[8].index': index
                })
              }
              if (ele.name == that.data.formData.type) {
                that.setData({
                  'showData.type': ele.name,
                  'formData.type': ele.id,
                  'formlist[8].index': index
                })
              }
            })
          }
          that.setData({
            'formlist[8].data': res.data.data
          })
        }
      }
    })
  },
  textareaChange:function(e){
      this.setData({
        'formData.anyMore': e.detail.value
      })
  },
  checkEducation:function(){
    var data = this.data.formData;
    if ((data.highSchoolName != '') || (data.highSchoolStart != '') || (data.highSchoolEnd != '') || (data.universityName != '') || (data.universityStart != '') || (data.universityEnd != '') || (data.graduateStudentName != '') || (data.graduateStudentStart != '') || (data.graduateStudentEnd != '') || (data.topSchoolName != '') || (data.topSchoolStart != '') || (data.topSchoolEnd != '')){
      this.setData({
        'formData.educationExp':'已填写'
      })
    }
    if ((data.brandCar != '') && (data.plateNumber != '') && (data.carColor != '') && (data.seat != '')) {
      this.setData({
        'formData.carDetail': '已填写'
      })
    }
  },
  checkReg: function (data) {
    var flag = true;
    for (var i = 0; i < data.length; i++) {
      if (data[i].reg) {
        var reg = new RegExp(data[i].reg);
        if (!reg.test(''+this.data.formData[data[i].key])) {
          flag = false;
          this.setData({
            'modelData.showModal': true,
            'modelData.content': '请输入正确的' + data[i].label
          });
          return;
        }
      }
    }
    return flag;
  },
  saveInfo:function(e){
    var _this=this;
    if (this.data.canSubmit){
      if (this.checkReg(this.data.formlist) == true) {
      var param = {};
      if (this.data.isHome) {
        this.data.formData.birthday = this.data.formData.cardId.substr(6, 4) + '-' + this.data.formData.cardId.substr(10, 2) + '-' + this.data.formData.cardId.substr(12, 2);
      }
      for (var j in this.data.formData){
        if (j != 'carDetail' && j != 'educationExp' && j !='brandCarName'){
          param[j] = this.data.formData[j];
        }
      }
      param.type = param.type+'';
      if (typeof (param.homeplace) =='object'){
        param.homeplace = param.homeplace.join(',');
      }
      wx.request({
        url: app.globalData.httpApiCar + 'tGyUserInfo/update',
        data: param,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success){
            for (var j in _this.data.formData) {
              // if (this.data.userInfo[j]) {
              _this.data.userInfo[j] = _this.data.formData[j];
              // }
            }
            wx.setStorageSync('userInfo', JSON.stringify(_this.data.userInfo));
            var url = '';
            if (_this.data.error != 1){
              url = _this.data.isHome ? '/pages/home/home' : '/pages/wholeMine/wholeMine';
            }
            else{
              url = '/pages/brandBusiness/brandBusiness'
            }
            wx.redirectTo({
              url: url
            })
          }
        }
      })
    }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  uploadImg:function(e){
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      // sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        let key = e.currentTarget.dataset.key;
        var tempFilePaths = res.tempFilePaths;
        that.upload(tempFilePaths);
        
      }
    })
  },
  /*上传图片*/
  upload: function (path) {
    var that = this;
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    }),
      wx.uploadFile({
        url: app.globalData.httpApiCar + 'uploadfile/upload1',
        filePath: path[0],
        name: 'file',
        header: { "Content-Type": "multipart/form-data" },
        formData: {},
        success: function (res) {
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
          var url = JSON.parse(res.data).data;
          that.setData({
            'formData.imgUrl': url
          })
          that.changeValue();
        },
        fail: function (e) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
  },
  changeTextarea: function (e) {//其他需求textarea值改变事件
    var key = e.target.dataset.value;
    this.data.formData[key] = e.detail.value;
    this.setData({
      formData: this.data.formData
    })
    this.changeValue();
  },
  inputTap: function (e) {
    wx.setStorage({
      key: 'personalInfo',
      data: this.data.formData,
    })
    if(this.data.isHome){
      wx.navigateTo({
        url: e.currentTarget.dataset.url+'?isHome',
      })
    }else{
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
    
  },
  changeValue() {
    var flag = true;
    var item = this.data.formData;
    if ((item.name == '') || (item.homeplace == '') || (item.imgUrl == '') || (item.street == '') || (item.cardId == '') || (item.address == '') || (item.phone == '') || (item.type == '')) {
      flag = false;
    }
    this.setData({
      canSubmit: flag
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    wx.getStorage({
      key: 'personalInfo',
      success: function (res) {
        that.setData({
          formData: res.data
        })
        that.changeValue();
        that.checkEducation();
        that.getAllType();
        wx.removeStorage({
          key: 'personalInfo'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})